<template>
    <el-container>
        <el-header v-if="!isDisabled">
            <el-button
                    @click="item_moveUp"
                    v-if="itemIndex !== 0"
                    type="primary"
                    icon="el-icon-upload2"
                    circle></el-button>
            <el-button
                    @click="item_moveDown"
                    v-if="itemIndex !== answerCount-1"
                    type="success"
                    icon="el-icon-download"
                    circle></el-button>
            <el-button
                    @click="item_delQuestion"
                    type="danger"
                    icon="el-icon-delete"
                    circle></el-button>
        </el-header>
        <el-main>
            <el-form
                    ref="dataForm"
                    :model="item_que"
                    label-position="center"
                    label-width="130px"
                    :class="[isDisabled?'normal':'no_normal']"
            >
                <svg-icon v-if="item_que.required === 1" icon-class="必填" style="width:32px;height:32px;float: left;margin-right:5px"/>
                <p style="font-size: 18px;color: #3b91b6">级联题</p>
                <el-row :gutter="10">
                    <el-col :span="6">
                        <el-form-item
                                label="排序："
                                prop="viewSort"
                        >
                            <el-input  v-model="item_que.viewSort"  type="text" placeholder="问题序号,如1/I/一/①..." class="inputBox" :disabled="isDisabled"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="18">
                        <el-form-item
                                label="问题描述："
                                prop="title"
                        >
                            <el-input  v-model="item_que.title"  type="text" placeholder="问题描述..." class="inputBox" :disabled="isDisabled"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item
                        label="问题备注："
                        prop="description"
                >
                    <el-input  v-model="item_que.description"  type="text" placeholder="问题备注..." class="inputBox" :disabled="isDisabled"></el-input>
                </el-form-item>
                <!--未选中时显示的样子-->
                <el-form-item
                        label="选项："
                        v-if="isDisabled"
                >
                    <el-cascader-panel :options="item_que.options" :props="props" ></el-cascader-panel>
                </el-form-item>

                <!--选中编辑时显示的样子-->
                <div v-if="!isDisabled">
                    <el-form-item>
                        <el-tree :data="item_que.options"
                                 node-key="id"
                                 default-expand-all
                                 :expand-on-click-node="false"
                                 @node-click="nodeclick"
                                 draggable
                                 :allow-drop="allowDrop"
                                 >
                            <span class="custom-tree-node"
                                  slot-scope="{ node, data }">

                                <!-- 如果是编辑状态 -->
                              <template v-if="data.isEdit==1">
                                    <el-input ref="input"
                                              @blur="() => submitEdit(node,data)"
                                              v-model="newApiGroupName"
                                              style="height:20px;line-height:20px"></el-input>
                              </template>
                                <!-- 如果不是编辑状态 -->
                              <span v-else
                                    v-text="data.label"></span>
                                <span>
                                    <el-button
                                            type="text"
                                            size="mini"
                                            @click="() => edit(node,data)">
                                      改
                                    </el-button>
                                    <el-button type="text"
                                               size="mini"
                                               @click="() => append(node,data)"
                                               v-if="data.isOther === 0"
                                    >
                                      +
                                    </el-button>
                                    <el-button
                                            type="text"
                                            size="mini"
                                            @click="() => remove(node, data)">
                                      删
                                    </el-button>
                                </span>

                            </span>
                        </el-tree>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="success" @click="addOp">新增根选项</el-button>
                        <!--<el-button type="info" @click="removeDeflut">取消默认选中</el-button>-->
                        <el-button type="primary" @click="addIsOther">增加自定义填写的'其他'选项</el-button>
                    </el-form-item>
                </div>

            </el-form>
            <el-collapse v-if="!isDisabled">
                <el-divider><i class="el-icon-s-tools"></i></el-divider>
                <el-collapse-item title="更多设置..." name="foot">
                    <el-form
                            ref="dataForm"
                            :model="item_que"
                            label-position="center"
                            label-width="120px"
                    >

                        <el-row :gutter="10">
                            <el-col :span="8">
                                <el-form-item
                                        label="是否可以多选："
                                >
                                    <el-radio v-model="item_que.isChildAnswer" :label=1>单选</el-radio>
                                    <el-radio v-model="item_que.isChildAnswer" :label=2>多选</el-radio>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item
                                        label="限选设置："
                                        v-if="item_que.isChildAnswer === 2"
                                >
                                    <el-select v-model="limit_selectNum" placeholder="请选择">
                                        <el-option
                                                v-for="item in numSelectOps"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item
                                        label="限选设置个数："
                                        v-if="limit_selectNum !== 0"
                                >
                                    <el-input-number v-model="item_que.selectNum" @change="selectNumChange" :min="2"  label="限制选项个数"></el-input-number>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row :gutter="10">
                            <el-col :span="12">
                                <el-form-item
                                        label="是否必填："
                                >
                                    <el-radio v-model="item_que.required" :label=0>否</el-radio>
                                    <el-radio v-model="item_que.required" :label=1>是</el-radio>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item
                                        label="必填校验提示："
                                >
                                    <el-input v-if="item_que.required===1"
                                              v-model="item_que.errorMsg"
                                              type="text" placeholder="此题必选!" class="inputBox"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="10">
                            <el-col :span="12">
                                <el-form-item
                                        label="是否常用："
                                >
                                    <el-radio v-model="item_que.isCommon" :label=0>不常用</el-radio>
                                    <el-radio v-model="item_que.isCommon" :label=1>常用</el-radio>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item
                                        label="状态："
                                >
                                    <el-radio v-model="item_que.status" :label=0>可用</el-radio>
                                    <el-radio v-model="item_que.status" :label=1>禁用</el-radio>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-collapse-item>
            </el-collapse>
        </el-main>
    </el-container>
</template>

<script>
    import  {new_options}  from '@/utils/newQuestion'
    import { get, post } from '@/utils/httpUtil'
    let id = 1000;
    export default {
        name: "item_chained",
        data() {
            return {
                item_que:JSON.parse(JSON.stringify(this.itemData)),
                new_option:JSON.parse(JSON.stringify(new_options)),
                limit_selectNum:0,
                numSelectOps: [{
                    value: 0,
                    label: '无限制'
                }, {
                    value: 1,
                    label: '最多选:'
                }, {
                    value: 2,
                    label: '最少选:'
                }],
                //复杂的可编辑树状
                newApiGroupName: '',
                // props: { multiple: true,expandTrigger: 'hover' },
                props: { expandTrigger: 'hover' },
            }
        },
        props: {
            itemData:Object,
            isDisabled:Boolean,
            answerCount:Number,
            itemIndex:Number,
            moveUp:Function,
            moveDown:Function,
            delQuestion:Function,
            itemUpDataItem:Function,
        },
        computed: {
            haveOther(){
                let bb = false
                this.item_que.options.forEach((item, index) => {
                    if(item.isOther === 1){
                        bb =  true
                    }
                });
                return bb
            },
            op_Other(){
                let onlyOther = {}
                this.item_que.options.forEach((item, index) => {
                    if(item.isOther === 1){
                        onlyOther =  JSON.parse(JSON.stringify(item))
                    }
                });
                return onlyOther
            }
        },
        watch: {
            isDisabled: function(newVal){
                this.gotUpData()
            },
            limit_selectNum: function (newVal) {
                this.item_que.selectNum = 0
            }
        },
        mounted(){
            if(this.item_que.selectNum === 0){

            }else if(this.item_que.selectNum >0){
                this.limit_selectNum = 1
            }else{
                this.limit_selectNum = 2
                let cc = this.item_que.selectNum
                this.item_que.selectNum = -cc
            }
        },
        methods: {
            item_delQuestion(){
                this.delQuestion(this.itemIndex)
            },
            item_moveUp(){
                this.moveUp(this.itemIndex)
            },
            item_moveDown(){
                this.moveDown(this.itemIndex)
            },
            //选择默认选项在级联不合适
            // deflutOp(item){
            //     let index = this.item_que.options.indexOf(item);
            //     let deflutOp = this.item_que.options[index];
            //     if(deflutOp.isOther === 1){
            //         this.$message({
            //             message: '用户填写项不能设为默认',
            //             type: 'warning'
            //         });
            //     }else{
            //         deflutOp.status=2;
            //         this.checkList.push(deflutOp.label)
            //         this.$set(this.item_que.options,index,deflutOp)
            //     }
            // },
            // removeDeflut(){
            //     this.checkList =[]
            //     this.item_que.options.forEach((item, index) => {
            //         item.status=0
            //     });
            // },
            addOp() {
                let newOp = Object.assign({}, this.new_option);
                newOp.id = id++
                newOp.isEdit = 0
                newOp.children = []
                this.item_que.options.push(newOp);
            },
            addIsOther(){
                if(!this.haveOther){
                    let newOp = Object.assign({}, this.new_option);
                    newOp.isOther = 1;
                    newOp.label = '其他....';
                    this.item_que.options.push(newOp);
                }else{
                    this.$message({
                        message: '只能有一个用户填写的自定义项',
                        type: 'warning'
                    });
                }

            },
            selectNumChange(value){
                this.item_que.selectNum = value
            },
            gotUpData(){
                if(this.limit_selectNum === 0){
                    this.item_que.selectNum = 0
                }else if(this.limit_selectNum === 1){
                }else {
                    let cc = this.item_que.selectNum
                    this.item_que.selectNum = 0-cc
                }
                this.itemUpDataItem(this.itemIndex,this.item_que);
            },
            //复杂的可编辑树状
            //拖拽
            allowDrop(draggingNode, dropNode, type) {
                if (draggingNode.parent === dropNode.parent) {
                    return type !== 'inner'
                }
                else return false
            },

            append(node, data) {
                let newOp = Object.assign({}, this.new_option);
                newOp.id = id++
                newOp.isEdit = 0
                newOp.children = []
                if (!data.children) {
                    this.$set(data, 'children', [])
                }
                data.children.push(newOp)
            },

            remove(node, data) {
                const parent = node.parent
                const children = parent.data.children || parent.data
                const index = children.findIndex(d => d.id === data.id)
                if(this.item_que.id){
                    if(typeof data.id === 'number'){
                        children.splice(index, 1)
                    }else{
                        //是不是新选项
                        this.$confirm('此操作将永久删除该选项, 是否继续?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            let redata = {
                                id: data.id
                            }
                            post("/questionOptions/delById", redata).then(response => {
                                if (response.result) {
                                    this.$message({
                                        type: 'success',
                                        message: '删除成功!'
                                    });
                                    children.splice(index, 1)
                                } else {
                                    this.$message({
                                        type: 'warning',
                                        message: '删除失败!'+response.msg
                                    });
                                }
                            })
                        }).catch(() => {
                            this.$message({
                                type: 'info',
                                message: '已取消删除'
                            });
                        });
                    }
                }else{
                    children.splice(index, 1)
                }



            },

            edit(node, data) {
                this.$set(data, 'isEdit', 1)
                this.newApiGroupName = data.label
                this.$nextTick(() => {
                    this.$refs.input.focus()
                })
                console.log('after:', data.id, data.label, data.isEdit)
            },

            submitEdit(node, data) {
                // console.log('点击了保存按钮')
                if (data.label == this.newApiGroupName) {
                    console.log('没有修改')
                    this.newApiGroupName = ''
                    this.$set(data, 'isEdit', 0)
                } else {
                    this.$set(data, 'label', this.newApiGroupName)
                    this.newApiGroupName = ''
                    this.$set(data, 'isEdit', 0)
                }
            },
            cancelEdit(node, data) {
                // console.log('放弃编辑')
                // console.log(data.id, data.apiGroupName)
                this.newApiGroupName = ''
                this.$set(data, 'isEdit', 0)
            },
            nodeclick(node, data, obj) {
                console.log('点击了：', node.id, node.label)
            },

        }

    }
</script>

<style scoped>
    .normal{
        width: 95%; margin-left:50px;background: #e3e3e3;border:1px solid #000;
    }
    .no_normal{
        width: 95%; margin-left:50px;background: #fff;border:1px solid #000;
    }
    .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 20px;
    }
    /* 修改el-input高度，方案一： */
    /* 某些预处理器(sass)无法识别>>>，建议使用方案二 */
    /* >>> .el-input__inner {
      height: 20px;
    } */
    /* 修改el-input高度，方案二： */
    /deep/ .el-input__inner {
        height: 20px;
    }
</style>
